package com.docking.heylo.service.impl;


import com.docking.heylo.ThreadContext;
import com.docking.heylo.dao.entity.SysRoleResources;
import com.docking.heylo.dao.entity.SysRoleResourcesExample;
import com.docking.heylo.dao.mapper.SysRoleResourcesMapper;
import com.docking.heylo.enums.EDeleteStatus;
import com.docking.heylo.service.ISysRoleResourceService;
import com.docking.heylo.web.dto.SysRoleResourcesDto;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class SysRoleResourceService implements ISysRoleResourceService {

    @Resource
    private SysRoleResourcesMapper roleResourcesMapper;


    @Override
    public void updateBatchRoleResources(SysRoleResourcesDto roleResourcesDto) {
        SysRoleResourcesExample example = new SysRoleResourcesExample();
        SysRoleResourcesExample.Criteria criteria = example.createCriteria();
        criteria.andRoleIdEqualTo(roleResourcesDto.getRoleId());
        criteria.andDeletedEqualTo(EDeleteStatus.notDeleted.getValue());
        List<SysRoleResources> dbResources = roleResourcesMapper.selectByExample(example);

        // 新增的
        List<SysRoleResources> newResource = roleResourcesDto.getResources().stream().filter(item -> {
            item.setRoleId(roleResourcesDto.getRoleId());
            return !dbResources.contains(item);
        }).collect(Collectors.toList());

        // 移除掉的
        List<SysRoleResources> delResource = dbResources.stream().filter(item -> {
            item.setRoleId(roleResourcesDto.getRoleId());
            return !roleResourcesDto.getResources().contains(item);
        }).collect(Collectors.toList());

        newResource.forEach(item -> {
            item.setCreateAt(new Date());
            item.setCreateBy(ThreadContext.userId());
            item.setDeleted(EDeleteStatus.notDeleted.getValue());
            roleResourcesMapper.insertSelective(item);
        });

        if(delResource.size() > 0){
            roleResourcesMapper.batchDelByPrimaryKey(delResource);
        }
    }

    @Override
    public List<Map<String, Object>> resourcesByRoleId(Integer roleId) {
        return roleResourcesMapper.resourcesByURoleId(roleId);
    }

    @Override
    public List<Map<String, Object>> resourcesByRoleId2(Integer roleId) {
        return roleResourcesMapper.resourcesByURoleId2(roleId);
    }
}
